<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2019/4/7
 * Time: 19:27
 */

namespace common\logics\cashrecord;

use Yii;
use yii\base\BaseObject;
use common\widgets\Tool;

class CashRecordLogic extends BaseObject implements ICashRecord
{
    /** @var \common\sources\read\cashrecord\CashRecordAccess  $RCashRecordAccess ***/
    private $RCashRecordAccess;
    /** @var \common\sources\write\cashrecord\CashRecordAccess $WCashRecordAccess ***/
    private $WCashRecordAccess;
    /** @var \common\sources\read\buyuser\BuyUserAccess  $RBuyUserAccess ***/
    private $RBuyUserAccess;
    /** @var \common\sources\read\businessacount\BusinessAcountAccess  $RBusinessAcountAccess ***/
    private $RBusinessAcountAccess;
    /** @var \common\sources\read\bank\BankAccess   $RBankAccess **/
    private $RBankAccess;
    /** @var \common\sources\write\businessacount\BusinessAcountAccess  $WBusinessAcountAccess ***/
    private $WBusinessAcountAccess;
    /** @var \common\sources\write\businessdepositrecord\BusinessDepositRecordAccess  $WBusinessDepositRecordAccess  **/
    private $WBusinessDepositRecordAccess;

    public function init()
    {
        $this->RCashRecordAccess = Yii::$container->get("RCashRecordAccess");
        $this->WCashRecordAccess = Yii::$container->get("WCashRecordAccess");
        $this->RBuyUserAccess = Yii::$container->get("RBuyUserAccess");
        $this->RBusinessAcountAccess = Yii::$container->get("RBusinessAcountAccess");
        $this->RBankAccess = Yii::$container->get("RBankAccess");
        $this->WBusinessAcountAccess = Yii::$container->get("WBusinessAcountAccess");
        $this->WBusinessDepositRecordAccess = Yii::$container->get("WBusinessDepositRecordAccess");
        parent::init(); // TODO: Change the autogenerated stub
    }

    public function getList($data)
    {
        if(empty($data['bus_id']))
        {
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],402,"安全码不能为空");
        }
        if($data['safetyCode'] != md5($data['bus_id']))
        {
            return Tool::returnJson([],403,"安全码不正确");
        }
        $count = $this->RCashRecordAccess->getCount($data);
        $list = [];
        if($count >0)
        {
            $list = $this->RCashRecordAccess->getList($data);
            foreach ($list as &$item)
            {
                $item['create_time'] =  isset($item['create_time']) ? date('Y-m-d H:i:s',$item['create_time']) : '';
                $item['cash_status_name'] = isset($item['cash_status']) ? Yii::$app->params['withdrawal_cash_status'][$item['cash_status']]  : "";
            }
        }
        return Tool::returnJson([
            "list" => $list,
            "page_num" => $data['page_num'],
            "count" => $count,
            "limit" => $data['limit']
        ],200,"成功");
    }
    //提现申请
    public function applyCash($data)
    {
        if(empty($data['bus_id']))
        {
            return Tool::returnJson([],401,"商家用户id不能为空");
        }
        if(empty($data['money']))
        {
            return Tool::returnJson([],402,"商家提现金额不能为空");
        }
        if(empty($data['pay_pwd']))
        {
            return Tool::returnJson([],403,"商家提现密码不能为空");
        }
        if(empty($data['ww_verify_img']))
        {
            return Tool::returnJson([],405,"商家店铺主旺旺截图不能为空");
        }
        $business = $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($business))
        {
            return Tool::returnJson([],406,"商家用户不存在");
        }
        $buyAccount = $this->RBusinessAcountAccess->getAcount($data['bus_id']);
        if(empty($buyAccount))
        {
            return Tool::returnJson([],407,"没有可以提现的押金");
        }
        if(empty($business['paypwd']) || $business['is_pay'] == 0)
        {
            return Tool::returnJson([],408,"没有设置提现密码");
        }
        //验证密码
        if (!Yii::$app->security->validatePassword($data['pay_pwd']."", $business['paypwd'])) {
            return Tool::returnJson([], 409, '提现密码错误');
        }
        if($buyAccount['ava_deposit'] < $data['money'])
        {
            return Tool::returnJson([], 410, '提现金额大于可用余额');
        }
        //验证绑定提现信息
        $bank_acount = $this->RBankAccess->getBuyUserBankAccount($data['bus_id']);
        if(empty($bank_acount))
        {
            return Tool::returnJson([], 411, '该商家没有绑定提现信息');
        }
        $serial_num = "ST".date('YmdHis',time()).rand(1000,9999);
        $cash_arr = [
            "bus_id" => $data['bus_id'],
            "money" => $data['money'],
            "arrival_money" => number_format($data['money']*0.997,2,".",""),
            "account_num" => $bank_acount['cardnum'],
            "ww_verify_img" => $data['ww_verify_img'],
            "username" => $bank_acount['real_name'],
            "serial_num" => $serial_num,
            "cash_status" => 1,
            "remark" => "提现押金",
        ];
        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try{
            $res = $this->WCashRecordAccess->addCashRecord($cash_arr);
            if($res)
            {
                //修改账号信息
                $bus_account = [
                    "total_deposit" => $buyAccount['total_deposit'],
                    "ava_deposit" => number_format($buyAccount['ava_deposit'] - $data['money'],2,".",""),
                    "cash_deposit" => number_format($buyAccount['cash_deposit']+ $data['money'],2,".",""),
                    "freezing_deposit" => $buyAccount['freezing_deposit'],
                    "bus_id" => $data['bus_id'],
                ];
                $cash_res = $this->WBusinessAcountAccess->withdrawalCash($bus_account);
                if($cash_res)
                {
                    //消耗押金记录
                    $deposits_arr =[
                        "bus_id" => $data['bus_id'],
                        'task_commod_id' => '0',
                        "task_id" => '',
                        'expend' => $data['money'],
                        'income' => 0,
                        'type' => 2,
                        'serial_num' => $serial_num,
                        "balance" => number_format($buyAccount['ava_deposit'] - $data['money'],2,".",""),
                        "freeze_change" => $data['money'],
                        "freeze_balance" => number_format($buyAccount['cash_deposit']+ $data['money'],2,".",""),
                        "remark" => '申请提现扣减押金',
                        "operatorId" => $business['phone'],
                    ];
                    $this->WBusinessDepositRecordAccess->addDepositRecord($deposits_arr);
                    $transaction->commit();
                    return Tool::returnJson([],200,"提现成功");
                }
                $transaction->rollBack();
                return Tool::returnJson([],412,"提现失败");
            }
            $transaction->rollBack();
            return Tool::returnJson([],412,"提现失败");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"提现异常".$e->getMessage());
        }
    }
    //撤销提现
    public function revoke($data)
    {
        if(empty($data['bus_id']))
        {
            return Tool::returnJson([],401,"商家id不能为空");
        }
        if(empty($data['cash_id']))
        {
            return Tool::returnJson([],402,"提现id不能为空");
        }
        if(empty($data['safetyCode']))
        {
            return Tool::returnJson([],403,"安全码不能为空");
        }
        if($data['safetyCode'] != md5($data['bus_id'].$data['cash_id']))
        {
            return Tool::returnJson([],405,"安全码不正确");
        }
        $business= $this->RBuyUserAccess->getBuyUserInfo($data['bus_id']);
        if(empty($business))
        {
            return Tool::returnJson([],406,"商家账号不存在");
        }
        $business_cash_record = $this->RCashRecordAccess->getCashDetail($data['cash_id']);
        if(empty($business_cash_record))
        {
            return Tool::returnJson([],407,"提现记录不存在");
        }
        //回复提现前
        $business_account = $this->RBusinessAcountAccess->getAcount($data['bus_id']);
        if(empty($business_account))
        {
            return Tool::returnJson([],408,"提现账号异常");
        }
        if($business_cash_record['cash_status'] !=1)
        {
            return Tool::returnJson([],412,"非待审核状态下不能审核");
        }

        //开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try{
            //修改提现记录状态
            $cash_res = $this->WCashRecordAccess->modifyCashRecord(['id' => $data['cash_id'],"cash_status" => 6]);
            if(!$cash_res)
            {
                $transaction->rollBack();
                return Tool::returnJson([],409,"申请提现失败");
            }
            //修改商家账号记录
            $bus_account = [
                "total_deposit" => $business_account['total_deposit'],
                "ava_deposit" => number_format($business_account['ava_deposit'] + $business_cash_record['money'],2,".",""),
                "cash_deposit" => number_format($business_account['cash_deposit']- $business_cash_record['money'],2,".",""),
                "freezing_deposit" => $business_account['freezing_deposit'],
                "bus_id" => $data['bus_id'],
            ];
            $bus_res = $this->WBusinessAcountAccess->withdrawalCash($bus_account);
            if(!$bus_res)
            {
                $transaction->rollBack();
                return Tool::returnJson([],410,"修改账号信息失败");
            }
            //增加押金记录信息
            $deposits_arr =[
                "bus_id" => $data['bus_id'],
                'task_commod_id' => '0',
                "task_id" => '',
                'expend' => 0,
                'income' => $business_cash_record['money'],
                'type' => 3,
                "balance" => number_format($business_account['ava_deposit'] + $business_cash_record['money'],2,".",""),
                "freeze_change" => -$business_cash_record['money'],
                "freeze_balance" => number_format($business_account['cash_deposit']- $business_cash_record['money'],2,".",""),
                "remark" => '撤销提现返还申请金额',
                "operatorId" => $data['bus_id'],
            ];
            $res = $this->WBusinessDepositRecordAccess->addDepositRecord($deposits_arr);
            if(!$res)
            {
                $transaction->rollBack();
                return Tool::returnJson([],411,"增加押金记录失败");
            }
            $transaction->commit();
            return Tool::returnJson([],200,"提现成功");
        }catch (\Exception $e)
        {
            $transaction->rollBack();
            return Tool::returnJson([],5000,"撤销异常".$e->getMessage());
        }
    }

}